export default {
  data() {
    return {
      T: null,
      map: null,
      mapRef: 'mapContent',
      defaultLonLat: [121.55038, 29.87772],
      markerTool: null,
      polygonTool: null,
      circleTool: null,
      coordinatePickup: null,
      currentPosition: null
    }
  },
  computed: {
    coverDefaultStyle() {
      return {
        color: 'blue',
        weight: 5,
        opacity: 0.5,
        fillColor: '#98DAF6',
        fillOpacity: 0.5,
        lineStyle: 'solid'
      }
    }
  },
  methods: {
    async init() {
      this.map = new this.T.Map(this.mapRef, {
        projection: 'EPSG:900913'
      })
      const [lon, lat] = this.defaultLonLat
      this.setCenterAndZoom(lon, lat, 10)
    },

    addMapEvent(eventName, callback) {
      this.removeMapEvent(eventName, callback)
      this.map.addEventListener(eventName, callback)
    },

    removeMapEvent(eventName, callback) {
      this.map.removeEventListener(eventName, callback)
    },

    setCenterAndZoom(lon, lat, zoom) {
      this.map.centerAndZoom(this.initialLngLat(lon, lat), zoom)
    },

    initialLngLat(lon, lat) {
      return new this.T.LngLat(lon, lat)
    },

    changeMapCursorStyle(cursorStyle) {
      this.map.getContainer().style.cursor = cursorStyle
    },

    addMarker(lon, lat) {
      const lonLat = this.initialLngLat(lon, lat)
      const marker = new this.T.Marker(lonLat)
      this.map.addOverLay(marker)
    },

    addCircleToMap(lon, lat, radius, style) {
      const defaultStyle = this.coverDefaultStyle

      const finalStyle = style || defaultStyle

      const circle = new this.T.Circle(this.initialLngLat(lon, lat), radius, finalStyle)
      this.map.addOverLay(circle)

      return circle
    },

    clearMarker() {
      this.map.clearOverLays()
    },

    removeOverLay(overLay) {
      this.map.removeOverLay(overLay)
    },

    createPolygonTool(style) {
      if (this.polygonTool) this.polygonTool.close()
      const defaultStyle = this.coverDefaultStyle
      defaultStyle.weight = 3
      const finalStyle = style || defaultStyle
      this.polygonTool = new this.T.PolygonTool(this.map, { showLabel: false, ...finalStyle })

      this.polygonTool.open()
    },

    // 创建坐标拾取
    createCoordinatePickup(callback) {
      this.coordinatePickup = new this.T.CoordinatePickup(this.map, { callback: callback })
      this.coordinatePickup.addEvent()
    },

    closeTools() {
      this.polygonTool?.close()
    },

    addPolygonToMap(points, style) {
      const defaultStyle = this.coverDefaultStyle
      const finalStyle = style || defaultStyle
      const polygon = new this.T.Polygon(points, finalStyle)
      this.map.addOverLay(polygon)

      return polygon
    },
    fitToOverlay(points) {
      const { center: { lng, lat }, zoom } = this.map.getViewport(points)
      console.log('lng, lat --------->', lng, lat)
      this.setCenterAndZoom(lng, lat, zoom)
    }
  }
}
